export const createData = (reducer, init) => {
  let data = init;

  let deps = [];

  const getData = () => data;

  const subscribe = (handler) => {
    // 订阅了这个数据的handler，在数据改变时，这个函数都能执行
    deps.push(handler);
  };

  const UNSAFE_changeData = (newData) => {
    data = newData;
    deps.forEach((fn) => fn());
  };

  const setDataByAction = (action) => {
    data = reducer(data, action);
    deps.forEach((fn) => fn());
  }

  return {
    getData,
    subscribe,
    UNSAFE_changeData,
    setDataByAction
  };
};
